package com.piano.moguyun.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import com.piano.moguyun.R;


/**
 * Activity 基类
 */

public class IBaseAct extends AppCompatActivity {
    protected String TAG = this.toString();
    protected int statusBarBgColorId = R.color.color_01;    // 状态栏背景颜色
    protected boolean isBlack = true;//状态栏文字颜色是否黑色
    protected Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (IBaseAct.this.isFinishing()) {
                return true;
            }
            return onHandleMessage(msg);
        }
    });
    /**
     * 获取实例
     *
     * @return MyApplication
     */
    private volatile static IBaseAct iBaseAct;
    public static IBaseAct getInstance() {
        if(iBaseAct == null){
            synchronized (IBaseAct.class){
                if(iBaseAct == null){
                    iBaseAct = new IBaseAct();
                }
            }
        }
        return iBaseAct;
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.i(TAG, "onCreate taskId = " + getTaskId());
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);  // 指定竖屏
        setStatusBar(statusBarBgColorId); // 修改状态栏颜色
    }


    protected boolean useThemestatusBarColor = true;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值
    protected boolean useStatusBarColor = false;//是否使用状态栏文字和图标为暗色，如果状态栏采用了白色系，则需要使状态栏和图标为暗色，android6.0以上可以设置


    /**
     *  // 修改状态栏颜色
     */
    protected void setStatusBar(int colorId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //09-02
            //if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
                //根据上面设置是否对状态栏单独设置颜色
                if (useThemestatusBarColor) {
                    getWindow().setStatusBarColor(getResources().getColor(colorId));
                } else {
                    getWindow().setStatusBarColor(Color.TRANSPARENT);
                }
            //}

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }

        // android6.0以后可以对状态栏文字颜色和图标进行修改
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !useStatusBarColor) {
            if (isBlack){
                //黑
                getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN| View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            }else{
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        LogUtils.i(TAG, "onNewIntent taskId = " + getTaskId());
        super.onNewIntent(intent);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    @Override
    protected void onStop() {
        LogUtils.i(TAG, "onStop taskId = " + getTaskId());
        super.onStop();
    }

    @Override
    protected void onResume() {
        LogUtils.i(TAG, "onResume taskId = " + getTaskId());
        super.onResume();
    }

    @Override
    protected void onPause() {
        LogUtils.i(TAG, "onPause taskId = " + getTaskId());
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        LogUtils.i(TAG, "onDestroy taskId = " + getTaskId());
		//DialogUtils.getInstance().dismissDialog();//09-01
        mHandler.removeCallbacksAndMessages(null);
        mHandler = null;
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    /**
     * edittext点击空白处失去焦点
     * @param v
     * @param event
     * @return
     */
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                //使EditText触发一次失去焦点事件
                v.setFocusable(false);
//                v.setFocusable(true); //这里不需要是因为下面一句代码会同时实现这个功能
                v.setFocusableInTouchMode(true);
                return true;
            }
        }
        return false;
    }
    protected boolean onHandleMessage(Message msg) {
        return false;
    }

    /**
     *
     * @param msg
     * @param type 类型 1:成功 2:错误 3:提示
     */
    protected void toast(String msg,int type) {
        ToastUtils.toast(msg,type);
    }


    //隐藏虚拟键盘
    public void showKeyboardByView(View view, boolean isShow) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        if (isShow) {
            imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        } else {
            if (imm.isActive()) {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
//                imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0); // 隐藏
            }
        }
    }
}
